﻿using PacketDotNet.Utils;
using Services.Equ.PcapCommunication.Abstract;
using SharpPcap;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;

namespace Services.Equ.PcapCommunication
{
    /// <summary>
    /// 升级设备通讯抽象类
    /// </summary>
    public class WriteCompleteCommunication : AbstractPcapCommunication<bool>
    {
        public FileInfo UpgradeFile { get; set; }
        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="upgradeFile">升级文件</param>
        /// <param name="destinationMac">设备mac地址</param>
        /// <param name="password">设备密码</param>
        /// <param name="device">所选网卡</param>
        public WriteCompleteCommunication(FileInfo upgradeFile, PhysicalAddress destinationMac, string password, ILiveDevice device) : base(destinationMac, password, device)
        {
            ReciveBreak = 1;
            UpgradeFile = upgradeFile;
            RpcType = 1;
            OptionType = 0x40005;
            DcpType = 0x40003;
            OpType = 4;
        }
        public override byte[] CreateBlockData()
        {
            using (var fs = UpgradeFile.OpenRead())
            {
                var data = new byte[fs.Length];
                fs.Read(data, 0, data.Length);
                Crc32 crc = new Crc32();
                var crcBytes = crc.ComputeHash(data);
                return crcBytes;
            }
        }
        public override bool IsResponse(byte[] bytes)
        {
            if (base.IsResponse(bytes)&&bytes.Length>80)
            {
                if (bytes[77] == 4 && (bytes[79] == 5 || bytes[79] == 6))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            return false;
        }
        public override bool ConvertData2Result(byte[] bytes)
        {
            return bytes[79] == 5;
        }
    }
}
